using AutoMapper;
using CustomerManagementSystem.Application;
using CustomerManagementSystem.Application.DTOs;
using CustomerManagementSystem.Domain.Entities;
using Microsoft.AspNetCore.Mvc;

namespace CustomerManagementSystem.API.Controllers;

[ApiController]
[Route("api/[controller]")]
public class CustomersController : ControllerBase
{
    private readonly ICustomerService _customerService;
    private readonly IMapper _mapper;

    public CustomersController(ICustomerService customerService, IMapper mapper)
    {
        _customerService = customerService;
        _mapper = mapper;
    }

    [HttpGet]
    public async Task<ActionResult<IEnumerable<CustomerDTO>>> GetAll()
    {
        var customers = await _customerService.GetAllCustomersAsync();
        return Ok(_mapper.Map<IEnumerable<CustomerDTO>>(customers));
    }

    [HttpGet("{id}")]
    public async Task<ActionResult<CustomerDTO>> GetById(Guid id)
    {
        var customer = await _customerService.GetCustomerByIdAsync(id);
        if (customer == null)
        {
            return NotFound();
        }
        return Ok(_mapper.Map<CustomerDTO>(customer));
    }

    [HttpPost("register")]
    public async Task<ActionResult<CustomerDTO>> Register(RegisterDTO registerDto)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        var customer = _mapper.Map<Customer>(registerDto);
        var createdCustomer = await _customerService.CreateCustomerAsync(customer);
        return CreatedAtAction(nameof(GetById), 
            new { id = createdCustomer.Id }, 
            _mapper.Map<CustomerDTO>(createdCustomer));
    }

    [HttpPost]
    public async Task<ActionResult<CustomerDTO>> Create(CustomerDTO customerDto)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        var customer = _mapper.Map<Customer>(customerDto);
        var createdCustomer = await _customerService.CreateCustomerAsync(customer);
        return CreatedAtAction(nameof(GetById), 
            new { id = createdCustomer.Id }, 
            _mapper.Map<CustomerDTO>(createdCustomer));
    }

    [HttpPut("{id}")]
    public async Task<IActionResult> Update(Guid id, CustomerDTO customerDto)
    {
        if (id != customerDto.Id)
        {
            return BadRequest();
        }

        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        var customer = _mapper.Map<Customer>(customerDto);
        await _customerService.UpdateCustomerAsync(customer);
        return NoContent();
    }

    [HttpDelete("{id}")]
    public async Task<IActionResult> Delete(Guid id)
    {
        await _customerService.DeleteCustomerAsync(id);
        return NoContent();
    }
}
